var cluster = require('cluster');
var http = require('http');
var os = require('os');

console.log('started master with ' + process.pid);

// 判断是否为主进程
if (cluster.isMaster) {
  const cpus = os.cpus();
  var numWorkers = cpus.length;
  console.log('Master cluster setting up ' + numWorkers + ' workers...');
  // 按照CPU的核数，新建若干个worker进程
  for (let i = 0, n = cpus.length; i < n; i++) {
    cluster.fork()
  }

  cluster.on('online', function (worker) {
    console.log('Worker ' + worker.process.pid + ' is online');
  })

  // worker进程挂掉通知主线程，主进程监听到worker进程挂掉的exit事件，就会重启一个进程
  // worker进程一旦启动成功，可以正常运行了，就会发出online事件。
  cluster.on('exit', function (worker, code, signal) {
    console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
    console.log('Starting a new worker');
    cluster.fork();
  })

  // 进程是worker进程，则在该进程启动一个服务器程序
} else {
  http.createServer(function (req, res) {
    res.writeHead(200)
    res.end('hello world')
  }).listen(3000)
}



